(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
      // here name is your name
      (global.util = factory());
}(this, (function () {

  if (typeof jQuery === undefined) {
    throw new Error('util needs jQuery')
  }
  var $ = jQuery

  window.TOKEN_KEY = 'token';
  window.host = "";

  /**
   * 
   *  发布到生产环境时务必去掉该行注释
   * 
  */
  window.host = 'http://api.rongsue.com';

  var utils = {
    host: window.host,
    ajax: function (obj) {
      /*
            if (!localStorage.token || (localStorage.exp - new Date().getTime()) < 0) {
                window.location.href = "/login.html?redirect_uri=" + encodeURIComponent(window.location.pathname);
                return;
            }

            obj.headers = {
                "Authorization": "Bearer " + localStorage.token
            }*/
      obj.url = window.host + obj.url;

      // 权限过滤
      if (
        location.pathname.indexOf('/channel/') > -1 &&
        utils.needChannelLogin() == false
      ) {
        return
      } else if (
        location.pathname.indexOf('/user/') > -1 &&
        utils.needMemberLogin()
      ) {
        return
      }

      if (obj.data) {
        // 去除对象内多余的空值key
        for (var key in obj.data) {
          if (obj.data[key] === '') {
            console.log('your lender delete field: ' + key + ' in ', obj)
            delete obj.data[key]
          }
        }
      }

      if (obj.type && obj.type.toLowerCase() === 'post') {
        obj.contentType = 'application/json'
        obj.data = JSON.stringify(obj.data)
      }

      var tokenHeader = utils.createAuthorizationTokenHeader()
      if (tokenHeader && tokenHeader.Authorization) {
        // xhr.setRequestHeader("Authorization", tokenHeader.Authorization);
        obj.headers = {
          Authorization: tokenHeader.Authorization
        }
      }

      obj.beforeSend = function () {
        $('body').append('<div class="global-ajax-layer"></div>')
      }

      obj.complete = function (xhr, stat) {
        // hide loading
        $('.loading').hide()
        $('.global-ajax-layer').remove()
      }

      // some times we should use error
      if (!obj.error) {
        obj.error = function (jqXHR, textStatus, errorThrown) {
          switch (jqXHR.status) {
            case 500:
              alert('服务器系统内部错误')
              break
            case 502:
              alert('502 Bad Gateway')
              break
            case 400:
              console.log(jqXHR)
              try {
                if (jqXHR.responseText) {
                  alert(JSON.parse(jqXHR.responseText).msg)
                }
              } catch (e) {
                alert('参数错误')
              }
              break
            case 401:
              alert('未登录')
              window.location.href =
                '/login.html?redirect_uri=' +
                encodeURIComponent(window.location.pathname)
              break
            case 403:
              alert('无权限执行此操作')
              // window.location.href = "/login.html?redirect_uri=" + encodeURIComponent(window.location.pathname);
              break
            case 408:
              alert('请求超时')
              break
            // img can not found will be a alert it's really hapi
            case 404:
              break
            case 0:
              // before send a XHR , window has being want to reload
              break
            default:
              console.log('default status', jqXHR.status)
              alert('未知错误')
          }
        }
      }

      return jQuery.ajax(obj)
    },
    /**
     * @param fileObj
     * @param cb
     */
    fileUpload: function (file, cb) {
      // 这里修改文件上传大小限制
      // 注意修改提示语
      
      if (file.size > 5242880) {
        alert('图片大于4MB,请压缩后上传')
        return
      }

      var formData = new FormData()
      formData.append('file', file)
      // 让提示出现的代码放在这里
      // 

      $('body').append('<div class="global-upload-layer">图片上传中，请耐心等待...</div>')
      $.ajax({
        url: this.host + '/common/file/upload',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        cache: false,
        success: function (res) {
          // 让提示消失的代码放在这里
          // 
          $(".global-upload-layer").remove();
          cb(res)
        }
      })
    },
    imgReview: function (src) {
      var img = new Image()
      img.src = src

      if (img.complete) {
        cb(img)
      } else {
        img.onload = cb
      }

      function cb(img) {
        var ww = window.innerWidth
        var wh = window.innerHeight

        var imgw = img.width
        var imgh = img.height
        // 横 true 竖 false
        var imgb = Boolean(imgw / imgh > 1)
        var cssobj = {}

        if (imgb) {
          if (ww < imgw) {
            cssobj['width'] = '100%'
            cssobj['margin-top'] = parseInt((wh - imgh / imgw * ww) / 2) + 'px'
          } else {
            cssobj['margin-top'] = parseInt((wh - imgh) / 2) + 'px'
          }
        } else {
          if (wh < imgh) {
            cssobj['height'] = '100%'
          } else {
            cssobj['margin-top'] = parseInt((wh - imgh) / 2) + 'px'
          }
        }
        $('body').append(
          '<div class="global-review-layer"><img src="" alt=""></div>'
        )
        $('.global-review-layer img')
          .attr('src', img.src)
          .css(cssobj)
        $('.global-review-layer').on('click', function () {
          $(this).remove()
        })
      }
    },

    //flush localstrong
    flushUserInfo: function (cb) {
      var userType = localStorage.userType
      var reqUrl = userType === 1 ? '/user/member' : '/user/manager'

      util.ajax({
        url: reqUrl,
        type: 'GET',
        headers: {
          Authorization: 'Bearer ' + localStorage.token
        },
        success: function (res) {
          // save userinfo into localstorage
          for (var item in res.data) {
            localStorage.setItem(item, res.data[item])
          }

          if (cb) {
            cb()
          }
        }
      })
    },
    getQuery: function () {
      // <<Professional JavaScript for Web Developers>> param BOM

      var qs = location.search.length > 0 ? location.search.substring(1) : '',
        args = {},
        items = qs.length ? qs.split('&') : [],
        item = null,
        name = null,
        value = null,
        i = 0,
        len = items.length

      for (i = 0; i < len; i++) {
        item = items[i].split('=')
        name = decodeURIComponent(item[0])
        value = decodeURIComponent(item[1])

        if (name.length) {
          args[name] = value
        }
      }
      return args
    },
    obj2query: function (obj) {
      var queryString = ''
      for (var item in obj) {
        queryString += '&' + item + '=' + obj[item].toString()
      }
      queryString = '?' + queryString.substring(1)
      return queryString
    },
    getUrlParam: function (name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
      var r = window.location.search.substr(1).match(reg)
      if (r != null) return unescape(r[2])
      return null
    },
    removeEmptyValue: function (data) {
      for (var key in data) {
        // 去除对象内多余的空值key
        if (data[key] === '') {
          delete data[key]
        }
      }
      return data
    },
    getJwtToken: function () {
      return localStorage.getItem(TOKEN_KEY)
    },
    setJwtToken: function (token) {
      localStorage.setItem(TOKEN_KEY, token)
    },
    removeJwtToken: function () {
      localStorage.removeItem(TOKEN_KEY)
    },
    isLogin: function () {
      return localStorage.token && localStorage.exp - new Date().getTime() > 0
    },
    needLogin: function () {
      if (utils.isLogin()) {
        return true
      }
      window.location.href =
        '/login.html?redirect_uri=' +
        encodeURIComponent(window.location.pathname)
      return false
    },
    needMemberLogin: function (warn) {
      if (utils.isLogin() && localStorage.userType == 1) {
        return true
      }
      if (warn) {
        alert('您还没有登录，请以会员身份登录')
      }
      window.location.href =
        '/login.html?redirect_uri=' +
        encodeURIComponent(window.location.pathname)
      return false
    },
    needChannelLogin: function (warn) {
      if (utils.isLogin() && localStorage.userType == 2) {
        return true
      }
      if (warn) {
        alert('您还没有登录，请以渠道经理身份登录')
      }
      window.location.href =
        '/login.html?redirect_uri=' +
        encodeURIComponent(window.location.pathname)
      return false
    },
    createAuthorizationTokenHeader: function () {
      var token = utils.getJwtToken()
      if (token) {
        return { Authorization: 'Bearer ' + token }
      }
      return {}
    },
    getPageItems: function (curPage, total, totalPages) {
      var pageItems
      if (totalPages <= 5) {
        pageItems = avalon.range(1, totalPages + 1)
      } else {
        if (curPage < 4) {
          pageItems = avalon.range(1, 6)
        } else if (curPage > 3 && curPage < totalPages - 1) {
          pageItems = avalon.range(curPage - 2, curPage + 3)
        } else {
          pageItems = avalon.range(totalPages - 4, totalPages + 1)
        }
      }
      return pageItems
    },
    diaplayTime: function (data) {
      var str = data
      //将字符串转换成时间格式
      var timePublish = new Date(str)
      var timeNow = new Date()
      var minute = 1000 * 60
      var hour = minute * 60
      var day = hour * 24
      var month = day * 30
      var diffValue = timeNow - timePublish
      var diffMonth = diffValue / month
      var diffWeek = diffValue / (7 * day)
      var diffDay = diffValue / day
      var diffHour = diffValue / hour
      var diffMinute = diffValue / minute

      if (diffValue < 0) {
        alert('错误时间')
      } else if (diffMonth > 3) {
        result = timePublish.getFullYear() + '-'
        result += timePublish.getMonth() + '-'
        result += timePublish.getDate()
        alert(result)
      } else if (diffMonth > 1) {
        result = parseInt(diffMonth) + '月前'
      } else if (diffWeek > 1) {
        result = parseInt(diffWeek) + '周前'
      } else if (diffDay > 1) {
        result = parseInt(diffDay) + '天前'
      } else if (diffHour > 1) {
        result = parseInt(diffHour) + '小时前'
      } else if (diffMinute > 1) {
        result = parseInt(diffMinute) + '分钟前'
      } else {
        result = '刚刚发表'
      }
      return result
    },
    // if null
    null2empty:function(obj){
      for (var i in obj)
      {
        if (obj[i] === null){
          obj[i]=''
        }
      }
      return obj
    },
    // wechat

    isWechat: function () {
      return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
    },
    appId: 'wx9b081da37eb41851',
    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard']
  }
  return utils
})))